package com.wt.dao;

import com.wt.entity.WqunCommunity;
import com.wt.entity.WqunCommunityBan;
import com.wt.util.jdbc.Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class WqunCommunityBanDao {
    //建立数据库连接，以便进行事务处理
    Connection con;
    {
        try {
            con = Util.getCon().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 查询数据库，方法由 service 层 调用
     */
    //实现化数据访问层中QueryRunner对象
    private QueryRunner qr = new QueryRunner(Util.getCon());

    public int isBan(String id){
        try {
            String sql = "SELECT count(*) FROM wqun_community_ban where `uid` = ? and `is_ban` = 1";
            Long count = (Long) qr.query(sql, new ScalarHandler(),id);
            return Math.toIntExact(count);
        } catch (SQLException throwables) {
            return 0;
        }
    }

    public List<WqunCommunityBan> getIsBan(String id){
        try {
            String sql = "SELECT id,uid,is_ban isBan,create_by createBy,created_time createdTime,modified_time modifiedTime,update_by updateBy FROM wqun_community_ban where uid=? and `is_ban` = 1";
            return qr.query(sql, new BeanListHandler<WqunCommunityBan>(WqunCommunityBan.class),id);
        } catch (SQLException throwables) {
            return null;
        }
    }

    public boolean updateById(int id){
        try {
            String sql =
                    "UPDATE wqun_community_ban  SET `is_ban` = 0 where id = ?";
            return  qr.update(sql,id) > 0;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    public boolean save(String id){
        try {
            String sql1 =
                    "insert into wqun_community_ban values(null,?,1,?,?,?,?) ";
            //调用 qr 对象中的方法 update 执行添加,自动添加
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String createdTime = simpleDateFormat.format(date);
            return qr.update(sql1, id,id,createdTime,createdTime,id)>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
}
